
package cell

import (
	"github.com/treelab/updatecolumn/models"
)

// InstanceType of cell
func InstanceType() int32 {
	return models.UniqueID
}

  cellValueToString({ cell }: IColumnAndCell) {
    return cell.uniqueId;
  }

  convertCell(
    command: UpdateColumn_v2,
    o: CommonOptions,
    helper: { rows: Row[]; columnCopy: Column; referenceColumns: Column[] },
  ) {
    const { column } = command;
    const { columnCopy, rows } = helper;
    const { type: toType } = command.columnConfig;
    const cells = column.hasCell.get();
    const columnConfig = command.columnConfig as UniqueIdColumnConfig;
    const cellRow: { [key: string]: Cell } = {};
    cells.forEach(cell => (cellRow[cell.rowId] = cell));
    if (this.needEmptyCell(command)) {
      this.instanceFactory.getCellInstance(columnCopy.columnType as ColumnType).emptyCells(command, cells, false, o);
    }
    const generateFn =
      columnConfig.idFormat === IDFormat.PREFIXHASH
        ? () => uuid(columnConfig.idPrefix || '')
        : () => dateuuid(columnConfig.idPrefix || '');

    if (rows.length) {
      const visableNameMapping = new Map<string, string>();
      _.forEach(rows, row => {
        // generate a new unique ID for the row
        const uniqueId = generateFn();
        const action = {
          type: UpdateAction.SET_VALUE,
          value: { ...command.columnConfig, uniqueId, type: toType },
        };
        const updateCell: UpdateCell_v2 = {
          ...command,
          action,
          rowId: row.uid!,
          _metadata: { ...command._metadata, source: Source.SAGA },
        };
        const rowData = super.upsertCell(cellRow[row.uid!], { command: updateCell }, o, { columnCopy });
        if (rowData) {
          visableNameMapping.set(rowData.uid, rowData.visibleName);
        }
      });
      this.updateReferenceColumnAndDependencies({
        column,
        visableNameMapping,
        o,
        _metadata: command._metadata,
        referenceColumns: helper.referenceColumns,
      });
    }

    return this;
  }

  setCellValue({ cell, action }: ICCAction) {
    cell.uniqueId = (action.value as UniqueIdCellValue).uniqueId;
    return this;
  }

  getCellValue(cell: Cell) {
    return cell.uniqueId;
  }

  emptyCells(command: UpdateColumn_v2, cells: readonly Cell[], deleteCells: boolean, o: CommonOptions) {
    if (!deleteCells) {
      _.forEach(cells, cell => {
        o.delQuads.push(...this.dgraphHelperService.getRemoveObjectQuads(cell.uid!, 'uniqueId'));
      });
    }
    super.emptyCells(command, cells, deleteCells, o);
    return this;
  }

